# -*- coding: utf-8 -*-
"""
Created on Tue May  5 16:48:19 2020

@author: RaingEye
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import time
#倒入时间模块

import warnings
warnings.filterwarnings('ignore')
#不发出警告

from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource, HoverTool
#导入bokeh绘图模块

'''
(1)生成样本数据，模拟实验
'''
sample1_m2 = create_sample(99, 'm')
sample1_f2 = create_sample(99, 'f')
sample1_m2['strategy'] = np.random.choice([1, 2, 3], 99)
#创建样本数据    

test_m2 = sample1_m2.copy()
test_f2 = sample1_f2.copy()
#复制实验数据，创建实验副本

n = 1
#设置一个实验次数变量

starttime = time.time()
#设置起始时间

success_roundn = different_strategy(test_m2, test_f2, n)
match_success2 = success_roundn
test_m2 = test_m2.drop(success_roundn['m'].tolist())
test_f2 = test_f2.drop(success_roundn['f'].tolist())

print('成功进行第%i轮试验，本轮实验成功匹配%i对，总共成功匹配%i对，还剩下%i位男性和%i为女性'%
      (n, len(success_roundn), len(match_success2), len(test_m2),len(test_f2)))
#第一轮测试


while len(success_roundn) != 0:
    n += 1
    success_roundn = different_strategy(test_m2,test_f2,n)   
    #得到该轮成功匹配数据
    match_success2 = pd.concat([match_success2,success_roundn])           
    # 将成功匹配数据汇总
    test_m2 = test_m2.drop(success_roundn['m'].tolist())
    test_f2 = test_f2.drop(success_roundn['f'].tolist())
    # 输出下一轮实验数据
    print('成功进行第%i轮实验，本轮实验成功匹配%i对，总共成功匹配%i对，还剩下%i位男性和%i位女性' % 
          (n,len(success_roundn),len(match_success2),len(test_m2),len(test_f2)))

endtime = time.time()
#记录结束时间
print('--------------------')
print('本次实验总共进行了%i轮，配对成功%i对\n---------------'%(n, len(match_success2)))
print('实验总共耗时%.2f秒'%(endtime - starttime))

'''
(2)生成绘制数据表格
'''
graphdata1 = match_success2.copy()
graphdata1 = pd.merge(graphdata1,sample1_m2,left_on = 'm',right_index = True)
graphdata1 = pd.merge(graphdata1,sample1_f2,left_on = 'f',right_index = True)
# 合并数据，得到成功配对的男女各项分值

graphdata1['x'] = '0,' + graphdata1['f'].str[1:] + ',' + graphdata1['f'].str[1:]
graphdata1['x'] = graphdata1['x'].str.split(',')
graphdata1['y'] = graphdata1['m'].str[1:] + ',' + graphdata1['m'].str[1:] + ',0'
graphdata1['y'] = graphdata1['y'].str.split(',')
# 筛选出id的数字编号，制作x，y字段

from bokeh.palettes import brewer
# 导入调色模块

round_num = graphdata1['round_n'].max()
color = brewer['Blues'][round_num+1]   # 这里+1是为了得到一个色带更宽的调色盘，避免最后一个颜色太浅
graphdata1['color'] = ''
for rn in graphdata1['round_n'].value_counts().index:
    graphdata1['color'][graphdata1['round_n'] == rn] = color[rn-1] 
# 设置颜色

graphdata1 = graphdata1[['m','f','strategy_type','round_n','score_x','score_y','x','y','color']]
# 筛选字段

# bokeh绘图
output_file('C:\\Users\\RaingEye\\Desktop\\数据分析项目实战\\婚恋配对实验\\pic1.html')
p = figure(plot_width=500, plot_height=500,title="配对实验过程模拟示意" ,tools= 'reset,wheel_zoom,pan')   # 构建绘图空间

for datai in graphdata1.values:
    p.line(datai[-3],datai[-2],line_width=1, line_alpha = 0.8, line_color = datai[-1],line_dash = [10,4],legend= 'round %i' % datai[3])  
    # 绘制折线
    p.circle(datai[-3],datai[-2],size = 3,color = datai[-1],legend= 'round %i' % datai[3])
    # 绘制点

p.ygrid.grid_line_dash = [6, 4]
p.xgrid.grid_line_dash = [6, 4]
p.legend.location = "top_right"
p.legend.click_policy="hide"
# 设置其他参数

show(p)

# 数据清洗

graphdata2 = match_success1.copy()
graphdata2 = pd.merge(graphdata2,sample1_m1,left_on = 'm',right_index = True)
graphdata2 = pd.merge(graphdata2,sample1_f1,left_on = 'f',right_index = True)
# 合并数据，得到成功配对的男女各项分值

graphdata2 = graphdata2[['m','f','apperance_x','character_x','fortune_x','apperance_y','character_y','fortune_y']]
# 筛选字段

graphdata2['for_m'] = pd.cut(graphdata2['fortune_x'],[0,50,70,500],labels = ['财低','财中','财高'])
graphdata2['cha_m'] = pd.cut(graphdata2['character_x'],[0,50,70,500],labels = ['品低','品中','品高'])
graphdata2['app_m'] = pd.cut(graphdata2['apperance_x'],[0,50,70,500],labels = ['颜低','颜中','颜高'])
graphdata2['for_f'] = pd.cut(graphdata2['fortune_y'],[0,50,70,500],labels = ['财低','财中','财高'])
graphdata2['cha_f'] = pd.cut(graphdata2['character_y'],[0,50,70,500],labels = ['品低','品中','品高'])
graphdata2['app_f'] = pd.cut(graphdata2['apperance_y'],[0,50,70,500],labels = ['颜低','颜中','颜高'])
# 指标区间划分

graphdata2['type_m'] = graphdata2['for_m'].astype(np.str) + graphdata2['cha_m'].astype(np.str) + graphdata2['app_m'].astype(np.str)
graphdata2['type_f'] = graphdata2['for_f'].astype(np.str) + graphdata2['cha_f'].astype(np.str) + graphdata2['app_f'].astype(np.str) 

graphdata2 = graphdata2[['m','f','type_m','type_f']]
# 筛选字段

# 匹配成功率计算

success_n = len(graphdata2)   #匹配成功的数据长度
success_chance = graphdata2.groupby(['type_m','type_f']).count().reset_index()#统计每一种类型匹配成功的数量
success_chance['chance'] = success_chance['m']/success_n   #计算每一种类型，匹配成功的成功概率
success_chance['alpha'] = (success_chance['chance'] - success_chance['chance'].min())/(success_chance['chance'].max() - success_chance['chance'].min())*8   # 设置alpha参数

# bokeh绘图
output_file('C:\\Users\\RaingEye\\Desktop\\数据分析项目实战\\婚恋配对实验\\pic2.html')
mlst = success_chance['type_m'].value_counts().index.tolist()
flst = success_chance['type_f'].value_counts().index.tolist()
source = ColumnDataSource(success_chance)    # 创建数据
hover = HoverTool(tooltips=[("男性类别", "@type_m"),
                           ("女性类别","@type_f"),
                           ("匹配成功率","@chance")]) # 设置标签显示内容

p = figure(plot_width=800, plot_height=800,x_range = mlst, y_range = flst,
           title="不同类型男女配对成功率" ,x_axis_label = '男', y_axis_label = '女',    # X,Y轴label
           tools= [hover,'reset,wheel_zoom,pan,lasso_select'])   # 构建绘图空间

p.square_cross(x = 'type_m', y = 'type_f', source = source,size = 18 ,color = 'red',alpha = 'alpha')
# 绘制点

p.ygrid.grid_line_dash = [6, 4]
p.xgrid.grid_line_dash = [6, 4]
p.xaxis.major_label_orientation = "vertical"
# 设置其他参数

show(p)












